﻿async function AJAXSubmit(oFormElement) {
    var message = $("#messageInput").val()
    if (!message) {
        return
    }
    const formData = new FormData(oFormElement);

    try {
        const response = await fetch(oFormElement.action, {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            response.json().then(function (json_resp) {
                var fileInput = document.getElementById('fileInput');
                if (fileInput) {
                    fileInput.outerHTML = fileInput.outerHTML;
                }
                document.getElementById('messageInput').value = "";
                
                connection.invoke("SendMessage", json_resp.data)
                    .catch(function (err) {
                        return console.error(err.toString());
                    });
            })
            
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

var more = function (min_id) {   
    $.get("?handler=More", { id: $("#minIdInput").val() },
        function (result) {
            if (result.ok) {
                $("#minIdInput").val(result.minId)
                if (result.minId == 1) {
                    $("#moreButton").hide();
                }
                if (result.data) {
                    result.data.forEach((item, index, array) => {
                        $("#messagesList").append(showMessage(item));
                    })
                }
            }
        });
}

var showMessage = function (data) {
    // Images
    var html_str = '<li><div class="timeline-time"><span class="time">' + data.time + '</span></div><div class="timeline-icon"><a href="javascript:;">&nbsp;</a></div>'
    html_str = html_str + '<div class="timeline-body"><div class="timeline-content">'
    if (data.images) {
        data.images.forEach((item, index, array) => {
            html_str = html_str + '<a href="/' + item + '"><img src="/' + item + '?width=960" /></a>'
        })
    }
    html_str = html_str + ' <p>' + data.user + '：' + data.message + '</p></div></div></li >'
    return html_str;
}

$(document).ready(function () {
   
    connection.on("ReceiveMessage", function (data) {
        $("#messagesList").prepend(showMessage(data))
    });
});